package com.hzsai.config;

import com.hzsai.interceptors.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

/**
 * hzsai 2019/7/31
 * usage: 拦截器注册
 **/
@Configuration
public class MyWebMvcConfigurator implements WebMvcConfigurer {

    private LocaleChangeInterceptor lci = null;

    /**
     * 编写拦截器，拦截所有controller
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // all interceptor in package `interceptor`
        InterceptorRegistration ir = registry.addInterceptor(new MyInterceptor());
        ir.addPathPatterns("/interceptor/*");

        // i18n localeChangeInterceptor
        // registry 是一个List<InterceptorRegistration>
        // InterceptorRegistration是一个包含了Interceptor和pattern的类
        // 即包含了拦截器(处理函数)和拦截匹配的模式
        InterceptorRegistration irr = registry.addInterceptor(localeChangeInterceptor());
        irr.addPathPatterns("/*");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("user/exportPDF").setViewName("/uep");
    }

    /**
     * 配置国际化拦截的参数
     * **当请求参数里面有language=???的时候，会进行拦截
     * **LocaleChangeInterceptor在实现的时候，继承了HandlerInterceptorAdapter
     * **实现了里面的preHandle方法，从而实现参数拦截，参数拦截后，会获取HttpServletRequest里面的参数
     * **并使用其来创建一个LocaleResolver，LocaleResolver再对这次请求的request和response进行新的Locale
     * **设置从而达到每一次请求国际化的目的
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        if (lci != null)
            return lci;

        lci = new LocaleChangeInterceptor();
        lci.setParamName("language");

        return lci;
    }

    /**
     * 国际化拦截器，这里需要确保bean名为localeResolver
     * @return
     */
    @Bean(name = "localeResolver")
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return slr;
    }
}
